package com.quesucede.gameoflife;

import java.util.HashSet;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Pair;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

/**
 * GridActivity manages the view and and buttons on screen. Provides
 * a listener for the buttons
 * @author Brett Kromkamp, William Sugarman, and Brian Pokrifka
 */
public class GridActivity extends Activity implements OnTouchListener{

	/**
	 * The underlying view for the grid
	 */
	private GridView _gridView;

	/**
	 * Called when the activity is first created.
	 * @param savedInstanceState - the saved state
	 * */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.grid);
		
		_gridView = (GridView)findViewById(R.id.grid_view);
		_gridView.setOnTouchListener(this);
	}
	
	
	/**
	 * Called when populating the options menu
	 * @param menu - the menu to populate from the XML
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	/**
	 * Listener used when menu option has been selected
	 * @param item - the selected item
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.settings:
				startActivity(new Intent(this, SettingsActivity.class));
				return true;
			case R.id.play_pause:
				_gridView.switchMode();
				if (_gridView.getMode() == GridView.PAUSE) {
					item.setTitle(R.string.play_label);
					item.setIcon(android.R.drawable.ic_media_play);
				}
				else {
					item.setTitle(R.string.pause_label);
					item.setIcon(android.R.drawable.ic_media_pause);
				}
				return true;
		}
		return false;
		
	}
	
	/**
	 * Listener used for the touch screen. Compiles a list of affected
	 * points and passes it off to the view to be processed
	 * @param v - the current view
	 * @event event - the event generated by the touch
	 */
	public boolean onTouch(View v, MotionEvent event)
	{
		int numPointers = event.getPointerCount();
		HashSet< Pair<Integer,Integer> > affectedPoints = new HashSet< Pair<Integer,Integer> >(numPointers);
		for(int i = 0; i < numPointers; i++)
		{
			int x = (int)event.getX(i) / Life.CELL_SIZE;
			int y = (int)event.getY(i) / Life.CELL_SIZE;
			affectedPoints.add(new Pair<Integer, Integer>(x,y));
		}
		_gridView.toggle(affectedPoints);
		return true;
	}
}